<template>
	<view>
		 <Header title="基本信息">
			<uv-icon name="arrow-left" size="18" color="#000" @click="goBack"></uv-icon>
		</Header>
		<view class="body">
			<view class="tx" @click="changeAvatar">
				<text class="info-label">头像</text>
				<view class="arrow-right">
					<!-- 动态绑定头像路径 -->
					<image class="img" :src="completeHeadImgUrl || '/static/imgs/tx.png'"></image>
					<uv-icon name="arrow-right" size="24" color="#dbdbdb"></uv-icon>
				</view>
			</view>
			
			<view class="info-item">
				<text class="info-label">姓名</text>
				<view class="box">
					<input v-model="user.name" placeholder="未填写" class="info-value" />
					<uv-icon name="arrow-right" size="24" color="#eaeaea"></uv-icon>
				</view>
			</view>
			<view class="info-item">
				<text class="info-label">性别</text>
				<view class="box">
					<view @click="openGenderPicker">
						<text class="info-value">{{ user.genderText || '未选择' }}</text>
						<uv-icon name="arrow-right" size="24" color="#eaeaea"></uv-icon>
					</view>
				</view>
			</view>
			<uv-picker 
				ref="genderPicker" 
				:columns="[genderOptions]" 
				@showToolbar="true" 
				:title="'选择性别'" 
				@confirm="onGenderConfirm" 
			></uv-picker>
			<view class="info-item">
				<text class="info-label">邮箱</text>
				<view class="box">
					<input v-model="user.email" placeholder="未填写" class="info-value" type="email" />
					<uv-icon name="arrow-right" size="24" color="#eaeaea"></uv-icon>
				</view>
			</view>
			<view class="info-item">
				<text class="info-label">电话</text>
				<view class="box">
					<input v-model="user.phone" placeholder="未填写" class="info-value" type="tel" />
					<uv-icon name="arrow-right" size="24" color="#eaeaea"></uv-icon>
				</view>
			</view>
			<!-- 修改生日字段 -->
			<view class="info-item" @click="openDateTimePicker">
				<text class="info-label">生日</text>
				<view class="box">
					<text class="info-value">{{ formattedDateTime }}</text>
					<uv-icon name="arrow-right" size="24" color="#eaeaea"></uv-icon>
				</view>
			</view>
			<!-- 新增备注字段 -->
			<view class="info-item">
				<text class="info-label">备注</text>
				<view class="box">
					<input v-model="user.description" placeholder="未填写" class="info-value" />
					<uv-icon name="arrow-right" size="24" color="#eaeaea"></uv-icon>
				</view>
			</view>
			
			<!-- 新增保存按钮 -->
			<view class="save-button" @click="saveUserInfo">
				<text>保存</text>
			</view>
			
			<view class="tc" @click="goBack">
				<text>退出登录</text>
			</view>
			
			<!-- 日期时间选择器 -->
			<view class="date-time-picker" v-show="showDateTimePicker">
				<view class="date-time-picker-header">
					<text @click="cancelDateTime">取消</text>
					<text @click="confirmDateTime">确定</text>
				</view>
				<view class="date-time-picker-content">
					<picker-view 
						:value="dateTimeValue" 
						@change="onDateTimeChange" 
						class="picker-view"
					>
						<picker-view-column>
							<view 
								class="picker-item" 
								v-for="(year, index) in years" 
								:key="index"
							>{{ year }}年</view>
						</picker-view-column>
						<picker-view-column>
							<view 
								class="picker-item" 
								v-for="(month, index) in months" 
								:key="index"
							>{{ month }}月</view>
						</picker-view-column>
						<picker-view-column>
							<view 
								class="picker-item" 
								v-for="(day, index) in days" 
								:key="index"
							>{{ day }}日</view>
						</picker-view-column>
						<picker-view-column>
							<view 
								class="picker-item" 
								v-for="(hour, index) in hours" 
								:key="index"
							>{{ hour }}时</view>
						</picker-view-column>
						<picker-view-column>
							<view 
								class="picker-item" 
								v-for="(minute, index) in minutes" 
								:key="index"
							>{{ minute }}分</view>
						</picker-view-column>
						<picker-view-column>
							<view 
								class="picker-item" 
								v-for="(second, index) in seconds" 
								:key="index"
							>{{ second }}秒</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import Header from '@/components/AppHeader/Header.vue';
import { getUserinfo, postUpdateInfo } from '@/api/weappUser'
import { ref, onMounted, computed, watch } from 'vue'

// 定义服务器的根地址
const API_BASE_URL = 'http://8.137.157.16:9999';

const user = ref({
  name: '',
  email: '',
  phone: '',
  gender: null, // 初始化为null，表示未选择
  genderText: '未选择', // 用于显示性别文本
  age: '', // 存储后端返回的完整生日字段
  description: '', // 新增备注字段
  headImgUrl: '' // 新增头像字段
})

const completeHeadImgUrl = computed(() => {
  // 如果 headImgUrl 是完整的 URL，则直接返回
  if (user.value.headImgUrl.startsWith('http://') || user.value.headImgUrl.startsWith('https://')) {
    return user.value.headImgUrl;
  }
  // 否则，拼接服务器根地址
  return API_BASE_URL + user.value.headImgUrl;
});

// 性别选择选项
const genderOptions = ['男', '女', '保密']

// 性别选择器引用
const genderPicker = ref(null)

// 打开性别选择器
const openGenderPicker = () => {
  genderPicker.value.open()
}

// 性别选择确认
const onGenderConfirm = (e) => {
  const selectedGenderText = e.value[0];
  user.value.genderText = selectedGenderText;

  const genderMap = {
    '男': 1,
    '女': 0,
    '保密': null
  }
  user.value.gender = genderMap[selectedGenderText];
};

const fetchUserinfo = async () => {
    try {
      const userId = uni.getStorageSync('userId');
      if (!userId) {
        console.error("用户ID不存在");
        return;
      }
      const res = await getUserinfo({ id: userId }); 
      console.log("基本信息返回数据：", res);
      if (res && res.data) {
        user.value.name = res.data.username || ''
        user.value.email = res.data.email || ''
        user.value.phone = res.data.phone || ''
        user.value.gender = res.data.gender
        user.value.age = formatDateForDisplay(res.data.age)
        user.value.description = res.data.description
        user.value.headImgUrl = res.data.headImgUrl || '' // 绑定头像路径
        
        user.value.genderText = genderTextFromValue(res.data.gender);
      }
    } catch (error) {
      console.error("获取基本信息失败：", error);
    }
};

// 计算属性：格式化日期和时间
const formattedDateTime = computed(() => {
  if (!user.value.age) return '未填写'
  return user.value.age;
})

// 根据后端返回的gender值设置显示文本
const genderTextFromValue = (genderValue) => {
  const genderMap = {
    1: '男',
    0: '女',
    null: '未选择',
  }
  return genderMap[genderValue] || '未选择';
}

const goBack = () => {
  uni.navigateBack();
};

// 保存用户信息
const saveUserInfo = async () => {
  try {
    const userId = uni.getStorageSync('userId');
    if (!userId) {
      uni.showToast({
        title: '用户ID不存在',
        icon: 'none'
      });
      return;
    }

    // 构建提交数据
    const updateData = {
      id: userId,
      username: user.value.name,
      name: user.value.name,
      gender: user.value.gender,
      age: formatDateForBackend(user.value.age),
      phone: user.value.phone,
      email: user.value.email,
      description: user.value.description,
      F_HeadImgUrl: user.value.headImgUrl
    };

    // 调用后端接口
    const res = await postUpdateInfo(updateData);
    console.log("修改个人信息返回数据：", res);

    if (res.code === 200) {
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: res.message || '保存失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error("保存个人信息失败：", error);
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    });
  }
};

// 更换头像
const changeAvatar = () => {
  uni.chooseImage({
    count: 1, // 默认9，设置为1表示只能选择一张图片
    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      // 这里需要上传图片到服务器，然后将服务器返回的路径赋值给user.headImgUrl
      uploadAvatar(tempFilePath);
    }
  });
};

// 上传头像到服务器
const uploadAvatar = (tempFilePath) => {
  const userId = uni.getStorageSync('userId');
  if (!userId) {
    uni.showToast({
      title: '用户ID不存在',
      icon: 'none'
    });
    return;
  }
  
  const uploadTask = uni.uploadFile({
    url: `${API_BASE_URL}/api/v1/user/uploadAvatar`, // 后端上传接口地址
    filePath: tempFilePath,
    name: 'file',
    formData: {
      userId: userId
    },
    success: (uploadRes) => {
      if (uploadRes.statusCode === 200) {
        try {
          const result = JSON.parse(uploadRes.data);
          if (result.code === 200 && result.data) {
            user.value.headImgUrl = result.data.avatarUrl; // 使用服务器返回的头像URL
            uni.showToast({
              title: '头像上传成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: result.message || '头像上传失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('上传头像响应解析失败:', error);
          uni.showToast({
            title: '头像上传失败',
            icon: 'none'
          });
        }
      } else {
        uni.showToast({
          title: `上传失败，状态码: ${uploadRes.statusCode}`,
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('上传头像失败:', err);
      uni.showToast({
        title: '上传失败，请检查网络',
        icon: 'none'
      });
    }
  });

  // 监听上传进度
  uploadTask.onProgressUpdate((res) => {
    console.log('上传进度:', res.progress, '%');
  });
};

// 日期时间选择器相关
const showDateTimePicker = ref(false);
const dateTimeValue = ref([0, 0, 0, 0, 0, 0]); // [年索引, 月索引, 日索引, 时索引, 分索引, 秒索引]
const years = ref([]);
const months = ref([]);
const days = ref([]);
const hours = ref([]);
const minutes = ref([]);
const seconds = ref([]);
const currentDate = ref(new Date());

// 生成年份数组 (1900-2050)
years.value = Array.from({ length: 2050 - 1900 + 1 }, (_, i) => 1900 + i);

// 生成月份数组 (1-12)
months.value = Array.from({ length: 12 }, (_, i) => i + 1);

// 生成小时数组 (0-23)
hours.value = Array.from({ length: 24 }, (_, i) => i);

// 生成分钟和秒数组 (0-59)
minutes.value = Array.from({ length: 60 }, (_, i) => i);
seconds.value = Array.from({ length: 60 }, (_, i) => i);

// 更新"日"的选择项，基于当前选择的年和月
const updateDays = () => {
  const selectedYear = years.value[dateTimeValue.value[0]];
  const selectedMonth = months.value[dateTimeValue.value[1]] - 1; // 月份从0开始
  
  const date = new Date(selectedYear, selectedMonth, 1);
  const daysInMonth = new Date(selectedYear, selectedMonth + 1, 0).getDate();
  
  // 生成当月的天数数组
  days.value = Array.from({ length: daysInMonth }, (_, i) => i + 1);
  
  // 如果当前选中的日期超出当月天数范围，则调整为当月最后一天
  if (dateTimeValue.value[2] >= days.value.length) {
    dateTimeValue.value[2] = days.value.length - 1;
  }
};

// 打开日期时间选择器
const openDateTimePicker = () => {
  showDateTimePicker.value = true;
  if (user.value.age) {
    // 解析日期时间字符串
    const date = new Date(user.value.age);
    const year = date.getFullYear();
    const month = date.getMonth();
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = 0; // 默认秒为0
    
    // 找到对应索引
    dateTimeValue.value = [
      years.value.indexOf(year),
      months.value.indexOf(month + 1),
      days.value.indexOf(day),
      hours.value.indexOf(hour),
      minutes.value.indexOf(minute),
      seconds.value.indexOf(second)
    ];
  } else {
    // 如果没有初始值，则使用当前日期，但秒设为0
    const now = new Date();
    dateTimeValue.value = [
      years.value.indexOf(now.getFullYear()),
      months.value.indexOf(now.getMonth() + 1),
      days.value.indexOf(now.getDate()),
      hours.value.indexOf(now.getHours()),
      minutes.value.indexOf(now.getMinutes()),
      seconds.value.indexOf(0) // 默认秒为0
    ];
  }
};

const cancelDateTime = () => {
  showDateTimePicker.value = false;
};

const confirmDateTime = () => {
  const selectedYear = years.value[dateTimeValue.value[0]];
  const selectedMonth = months.value[dateTimeValue.value[1]];
  const selectedDay = days.value[dateTimeValue.value[2]];
  const selectedHour = hours.value[dateTimeValue.value[3]];
  const selectedMinute = minutes.value[dateTimeValue.value[4]];
  const selectedSecond = seconds.value[dateTimeValue.value[5]];
  
  // 格式化日期时间字符串
  user.value.age = `${selectedYear}-${String(selectedMonth).padStart(2, '0')}-${String(selectedDay).padStart(2, '0')} ` +
                  `${String(selectedHour).padStart(2, '0')}:${String(selectedMinute).padStart(2, '0')}:${String(selectedSecond).padStart(2, '0')}`;
  
  showDateTimePicker.value = false;
};

const onDateTimeChange = (e) => {
  dateTimeValue.value = e.detail.value;
  // 更新"日"的选择项，因为月份或年份变化可能会影响当月的天数
  updateDays();
};

// 日期时间格式转换函数
const formatDateForDisplay = (dateTimeString) => {
  if (!dateTimeString) return '';
  const date = new Date(dateTimeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const formatDateForBackend = (displayDateTime) => {
  if (!displayDateTime) return null;
  return displayDateTime;
};

onMounted(() => {
  fetchUserinfo();
  updateDays(); // 确保在组件挂载时更新日数据
})
</script>

<style scoped lang="scss">
.body {
	border-top: 2rpx solid #f1f1f1;
}

.tc {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
}

.tx {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-top: 10rpx;
	padding-bottom: 10rpx;
	padding-left: 30rpx;
	border-bottom: 2rpx solid #f1f1f1;
	.img {
		height: 75rpx;
		width: 75rpx;
		border-radius: 50%;
	}
	.arrow-right {
		display: flex;
		padding-right: 30rpx;
	}
}

.info-label {
  font-size: 32rpx;
  color: #343434;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  .box {
    display: flex;
    align-items: center;
  }
}

.info-item:not(.no-border) {
  border-bottom: 2rpx solid #f1f1f1;
}

.info-value {
  font-size: 32rpx;
  color: #999999;
  width: 100%;
  text-align: right;
  box-sizing: border-box;
}

.box view {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
}

/* 新增保存按钮样式 */
.save-button {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  background-color: #007aff;
  border-radius: 40rpx;
  margin: 30rpx;
  margin-top: 60rpx;
  margin-bottom: 100rpx;
  text {
    color: white;
    font-size: 32rpx;
  }
}

/* 日期时间选择器样式 */
.date-time-picker {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: white;
  z-index: 999;
}

.date-time-picker-header {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f1f1f1;
}

.date-time-picker-header text {
  font-size: 32rpx;
}

.date-time-picker-content {
  height: 400rpx;
  overflow: hidden;
}

.picker-view {
  width: 100%;
  height: 300rpx;
}

.picker-item {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  font-size: 32rpx;
  color: #343434;
}
</style>